import axios from "axios";

const { createSlice } = require("@reduxjs/toolkit");


const foodsStore = createSlice({

    name: 'foods',
    initialState: {
        foodsList: [],
        activeIndex: 0,
        cartList: []
    },
    reducers: {
        setFoodsList(state, action) {
            state.foodsList = action.payload;
        },
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload;
        },
        addCart(state, action) {
            // 是否存在， action.payload.id 匹配
            const item = state.cartList.find(item => item.id === action.payload.id);
            if (item) {
                item.count++;
            } else {
                action.payload.count = 1;
                state.cartList.push(action.payload);
            }
        },
        clearCart(state) {
            state.cartList = []
        },
        incrementCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id);
            if (item) {
                item.count++;
            }
        },
        decrementCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id);
            if (item) {
                if (item.count <= 1) {
                    const itemIndex = state.cartList.find(item => item.id === action.payload);
                    state.cartList.splice(itemIndex, 1);
                    state.cartList = [
                        ...state.cartList
                    ]
                } else {
                    item.count--;
                }
            }
        }
    }
});

const foodsReducer = foodsStore.reducer;
// action creator
const { setFoodsList, changeActiveIndex, addCart, clearCart, incrementCount, decrementCount } = foodsStore.actions;

// async get data
const innerGetFoodsList = () => {
    return async (dispatch) => {
        const res = await axios.get('http://localhost:3004/takeaway');
        // call dispatch commit action, setFoodsList is action creator, parameter is payload
        dispatch(setFoodsList(res.data));
    };
}

export { setFoodsList, changeActiveIndex, addCart, clearCart, incrementCount, decrementCount, innerGetFoodsList };
export default foodsReducer;